﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Cost.Models;
using NBlock;

namespace Cost.Services
{
    public class PrivilegeService
    {
        #region 构造函数

        ICostRepository<Privilege> _Repo;
        public PrivilegeService(ICostRepository<Privilege> repo)
        {
            _Repo = repo;
        }
        #endregion

        public void SavePrivilege(Privilege data)
        {
            // 处理父节点，如果是根节点，则为空字符串
            data.ParentId = data.ParentId ?? string.Empty;
            data.ParentCode = data.ParentCode ?? string.Empty;
            data.ParentName = data.ParentName ?? string.Empty;
            _Repo.Save(data);
        }

        /// <summary>
        /// 获取指定Id的权限
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public Privilege GetPrivilege(string Id, string parentId = null)
        {
            var data = _Repo.Find(Id);
            if (data == null)
            {
                data = new Privilege();
                data.SeqNo = 9999;
                data.PrivilegeTypeEnum = PrivilegeType.Menu;

                var parent = _Repo.Find(parentId);
                if (parent != null)
                {
                    data.ParentCode = parent.PrivilegeCode;
                    data.ParentId = parent.Id;
                    data.ParentName = parent.PrivilegeName;
                }
            }
            else
            {
                var parent = _Repo.Find(data.ParentId);
                if (parent != null)
                {
                    data.ParentName = parent.PrivilegeName;
                }
            }
            return data;
        }

        /// <summary>
        /// 获取指定父节点的组织机构
        /// </summary>
        /// <param name="parentId">父节点Id</param>
        /// <returns></returns>
        public IList<Privilege> GetPrivilegesByParentId(string parentId)
        {
            if (string.IsNullOrEmpty(parentId))
            {
                return _Repo.FindAll().OrderBy(p => p.SeqNo).ToList();
            }
            else
            {
                return _Repo.FindAll(p => p.FullPath.Contains(parentId)).OrderBy(p => p.SeqNo).ToList();
            }
        }
    }
}